#ifndef _MQTT_H
#define _MQTT_H

// #include <PubSubClient.h>
// psc.h为PubSubClient.h的改写，作者Nick O'Leary（http://knolleary.net）。由于默认情况下只能接受128字节的数据，为了便于使用，故将此库文件改写。其他内容均未改动。
#include "psc.h"

WiFiClient esp_client;
PubSubClient client(esp_client);

// client id 的长度
#define client_id_len 20
#define split_code "@:-!"
// client id 随机生成
char client_id[client_id_len];



extern void check_btn();

// 声明函数
void mqtt_init();
void create_client_id();
void mqtt_callback(char *topic, byte *payload, unsigned int length);
void reconnect();
void send_code_to_server();

void mqtt_init() {
	// 设置服务器
	client.setServer(mqtt_server, port);
	// 设置回调
	client.setCallback(mqtt_callback);
	flag_mqtt_init = true;
}

// 生成client id
void create_client_id()
{
	randomSeed(analogRead(0));
	for (int i = 0; i < client_id_len; i++)
	{
		int rand_num = random(arr_len);
		client_id[i] = char(w[rand_num]);
	}
}

// 处理MQTT消息
void mqtt_callback(char *topic, byte *payload, unsigned int length)
{
	String rec_msg = "";
	String rec_callsign = "";
	int flag_rcd_callsign = 1;
	Serial.print("[MSG] ");
	for (int i = 0; i < length; i++)
	{
		rec_msg += (char)payload[i];
		// 记录发送者的呼号
		if ((char)payload[i] != ':' && flag_rcd_callsign != 0)
		{
			rec_callsign += (char)payload[i];
		}
		else
		{
			flag_rcd_callsign = 0;
		}
	}
	Serial.println(rec_msg);
	// 如果呼号不是自己的，则播放
	if (rec_callsign != String(callsign) || s_play_my_code)
	{
		play_code(rec_msg);
	}
}

// 连接MQTT
void reconnect()
{
	if (flag_net)
	{
		Serial.print("尝试连接MQTT...");
		d_home_update("info", "MQTT...");
		while (!client.connected() && flag_net)
		{
			check_btn();
			if (client.connect(client_id) && flag_net)
			{
				client.subscribe(topic_name);
				Serial.println("连接成功");
				d_home_update("info", "MQTT...OK");
			}
		}
	}
}

// 发送电码
void send_code_to_server()
{
	if (flag_net)
	{
		Serial.println();
		Serial.print("正在发送...");
		String send_msg = String(callsign) + ":" + send_code;
		int msg_length = send_msg.length();
		if (msg_length > 0)
		{
			client.beginPublish(topic_name, msg_length, false);
			// 拆分要发送的内容，50字符一个分段
			int i = 0;
			int block_num = 50;
			while (i * block_num < msg_length)
			{
				int end_num = (i + 1) * block_num;
				if(end_num > msg_length) {
					end_num = msg_length;
				}
				String temp_send_msg = send_msg.substring(i * block_num, end_num);
				Serial.println(temp_send_msg);
				client.print(temp_send_msg);
				i++;
			}
			client.endPublish();
		}
		Serial.println("完成");
		d_text_info = "Sent";
	}
	else
	{
		Serial.println("完成");
	}
	flag_d_ref = 1;
	send_code = "";
	flag_send = 0;
}

#endif
